﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Data.Entity;

namespace Elf.Data.Entity.Management
{
    /// <summary>
    /// The application request context.
    /// </summary>
    public class ApplicationRequestContext : IExtension<OperationContext>
    {
        /// <summary>
        /// Gets the current ApplicationRequestContext.
        /// </summary>
        public static ApplicationRequestContext Current
        {
            get { return OperationContext.Current.Extensions.Find<ApplicationRequestContext>(); }
        }

        #region IExtension<OperationContext> Members
        /// <summary>
        /// Attaches the specified owner.
        /// </summary>
        /// <param name="owner">The owner.</param>
        public void Attach(OperationContext owner) { }

        /// <summary>
        /// Detaches the specified owner.
        /// </summary>
        /// <param name="owner">The owner.</param>
        public void Detach(OperationContext owner) { }
        #endregion

        /// <summary>
        /// Adds to operation context.
        /// </summary>
        public static void AddToOperationContext()
        {
            OperationContext.Current.Extensions.Add(new ApplicationRequestContext());
        }

        /// <summary>
        /// Removes from operation context.
        /// </summary>
        public static void RemoveFromOperationContext()
        {
            if (ApplicationRequestContext.Current.DbContext != null)
                ApplicationRequestContext.Current.DbContext.Dispose();

            OperationContext.Current.Extensions.Remove(ApplicationRequestContext.Current);
        }

        /// <summary>
        /// Gets or sets the db context.
        /// </summary>
        /// <value>
        /// The db context.
        /// </value>
        public DbContext DbContext { get; set; }

    }
}
